package info.sean.main.groupingby;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

public class TestEmployee {


    //-------------------生成测试数据---------------------
    private List<Employee> getEmps(){
        List<Employee> list = new ArrayList<>();
        Random rd = new Random();
        String[] citys = {"北京","上海","广州","杭州","深圳"};
        String[] firstName = {"张","李","杨","宁","刘","王","高","葛"};
        Integer[] sales = {100,50,30,20};

        for (int i = 0; i < 10; i++) {
            String city = citys[rd.nextInt(5)];
            Integer sale = sales[rd.nextInt(4)];
            String fname = firstName[rd.nextInt(firstName.length)];

            list.add(new Employee(fname,city,sale));
        }

        return list;
    }



    /**
     *  groupBy方法1，groupingBy(Function)
     *
     *  要求：先按city分组，每个分组里面是一个员工集合
     */
    @Test
    public void test5(){
        List<Employee> emps = getEmps();

        Map<String, List<Employee>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity));

        map.forEach((key,val)->{
            System.out.println("城市："+key+" ---员工集： "+val);
        });
    }
    /**
     * 城市：广州 ---员工集： [Employee{name='1', city='广州', sales=100}, Employee{name='5', city='广州', sales=20}, Employee{name='6', city='广州', sales=30}, Employee{name='8', city='广州', sales=30}]
     * 城市：上海 ---员工集： [Employee{name='0', city='上海', sales=30}]
     * 城市：杭州 ---员工集： [Employee{name='2', city='杭州', sales=50}, Employee{name='7', city='杭州', sales=30}]
     * 城市：北京 ---员工集： [Employee{name='3', city='北京', sales=30}, Employee{name='4', city='北京', sales=50}, Employee{name='9', city='北京', sales=30}]
     */

    /**
     *  groupBy方法2，groupingBy(Function,Collector)
     *
     *  要求：先按city分组 ，再对组里面的成员，统计总销售额
     */
    @Test
    public void test3(){
        List<Employee> emps = getEmps();
        for (Employee emp : emps) {
            System.out.println(emp);
        }

        Map<String, Integer> map = emps.stream().
                collect(Collectors.groupingBy(Employee::getCity, Collectors.summingInt(Employee::getSales)));
        //                                    先按city分组                                  再对组里面的成员，统计总销售额
        map.forEach((key,val)->{
            System.out.println("城市："+key+" 销售总额："+val);
        });
    }
    /**
     * Employee{name='0', city='上海', sales=50}
     * Employee{name='1', city='广州', sales=20}
     * Employee{name='2', city='广州', sales=30}
     * Employee{name='3', city='广州', sales=20}
     * Employee{name='4', city='杭州', sales=30}
     * Employee{name='5', city='杭州', sales=50}
     * Employee{name='6', city='北京', sales=50}
     * Employee{name='7', city='广州', sales=20}
     * Employee{name='8', city='杭州', sales=100}
     * Employee{name='9', city='广州', sales=30}
     * 城市：广州 销售总额：120
     * 城市：上海 销售总额：50
     * 城市：杭州 销售总额：180
     * 城市：北京 销售总额：50
     */



}
